package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author RMY
 * @Date 2021/11/24 18:48
 * @Version 1.0
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    //网关过滤
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取url，并做出是否为登录请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //2.1作出判断，如果是就直接去登陆，不是要判断是否携带token
        if (path.contains("/login/in")){
            //放行到admin服务
            return chain.filter(exchange);
        }
        //2.2不是登录请求则判断是否携带token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            //没有token,则没有权限给他401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        //2.3检查token是否正确
        try {
            Payload payload = JwtUtils.getInfoFromToken(token);//payload是负荷
            Integer userId = payload.getUserId();
            //2.4将用户id放入header中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(userId));
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            //日志
            log.error("验证token时出错");
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        //返回链
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
